//
//  XFYVideoView.m
//  SDKSample
//
//  Created by 小肥羊 on 15/6/5.
//  Copyright (c) 2015年 Zhu‘s Game House. All rights reserved.
//

#import "XFYVideoView.h"

#define bottomHeight    (36.0)

@interface XFYVideoView ()

@property (nonatomic, strong) VMediaPlayer *mMPayer;                    /**< 视频播放器 */
@property (nonatomic, strong) UIActivityIndicatorView *activityView;    /**< 视频播放界面 */
@property (nonatomic, strong) UIImageView *bgImgView;                   /**< 默认背景 */
@property (nonatomic, strong) UIButton *playBtn;                        /**< 播放按钮 */
@property (nonatomic, strong) UIView *bottomView;                       /**< 底部视图 */
@property (nonatomic, strong) UIButton *changePlayBtn;                  /**< 切换播放按钮 */
@property (nonatomic, strong) UILabel *leftTime;                        /**< 当前播放时间 */
@property (nonatomic, strong) UILabel *rightTime;                       /**< 视频总长 */
@property (nonatomic, strong) VSegmentSlider *progressSld;              /**< 时长读条 */
@property (nonatomic, strong) UIButton *screenButton;                   /**< 全屏按钮 */
@property (nonatomic, strong) UIButton *volumnButton;                   /**< 声音按钮 */

@property (nonatomic, strong) NSTimer *mSyncSeekTimer;                  /**< 时间触发器 */


@property (nonatomic) CGRect oldframe;
@property (nonatomic, strong) NSURL *videoURL;      /**< 视频URL */
@property (nonatomic) BOOL isFullScreen;            /**< 是否全屏 */
@property (nonatomic) float mDuration;              /**< 播放进度 */
@property (nonatomic) BOOL progressDragging;        /**< 是否正在拖播放进度 */

@end


@implementation XFYVideoView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

#pragma mark - 初始化
-(id)initWithFrame:(CGRect)frame WithPlayUrl:(NSString *)PlayUrl withImgUrl:(NSString *)ImgUrl
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor grayColor];
        
        //界面
        if([ImgUrl isEqualToString:@""]||[ImgUrl isEqualToString:@"(null)"]){
            self.bgImgView.image = [UIImage imageNamed:@"wsmv_default"];
        }else{
            NSURL *url = [NSURL URLWithString:ImgUrl];
            [self.bgImgView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"news_list_loading"]];
        }
        [self addSubview: self.bgImgView];
        [self addSubview: self.activityView];
        [self addSubview: self.playBtn];
        
        //初始设置
        self.playUrl = PlayUrl;
        self.isFullScreen = NO;
        self.progressDragging = NO;
        
        [self drawBottomViewOrigion];
    }
    return self;
}

-(void)drawBottomViewOrigion{
    
    UIImageView *movieBackgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"wsmv_controlbar_bg"]];
    movieBackgroundImageView.frame = CGRectMake(0, 0, self.frame.size.width, bottomHeight);
    [self.bottomView addSubview:movieBackgroundImageView];
    [self.bottomView addSubview:self.changePlayBtn];
    [self.bottomView addSubview:self.leftTime];
    [self.bottomView addSubview:self.progressSld];
    [self.bottomView addSubview:self.rightTime];
    [self.bottomView addSubview:self.screenButton];
    [self.bottomView addSubview:self.volumnButton];
//
//    _isVoice=false;
//    
//    
//    //--------添加音量控制 begin-------------
//    Vslider = [[UISlider alloc] initWithFrame:CGRectMake(self.frame.size.width-80, (self.frame.size.height/2)-20,self.frame.size.height-64, 34)];
//    
//    
//    Vslider.frame=CGRectMake(self.frame.size.width-100, (self.frame.size.height/2)-20,self.frame.size.height-64, 34);
//    
//    MPMusicPlayerController *mpc = [MPMusicPlayerController applicationMusicPlayer];
//    
//    
//    
//    [Vslider setMinimumTrackTintColor:[UIColor greenColor]];
//    //设置已滑动位置背景图
//    
//    
//    [Vslider setMaximumTrackTintColor:[UIColor grayColor]];
//    
//    //设置图标图片
//    [Vslider setThumbImage:[UIImage imageNamed:@"wsmv_slider_thumb.png"] forState:UIControlStateNormal];
//    
//    
//    [Vslider setThumbImage:[UIImage imageNamed:@"wsmv_slider_thumb.png"] forState:UIControlStateHighlighted];
//    
//    
//    //设置旋转90度
//    Vslider.transform = CGAffineTransformMakeRotation(-M_PI / 2);
//    
//    //设置起始位置
//    Vslider.value=0.0;
//    //设置最小数
//    Vslider.minimumValue=0.0;
//    //设置最大数
//    Vslider.maximumValue=1.0;
//    Vslider.value = mpc.volume;
//    //设置背景颜色
//    Vslider.backgroundColor = [UIColor clearColor];
//    //设置委托事件
//    [Vslider addTarget:self action:@selector(musicVolume:) forControlEvents:UIControlEventValueChanged];
//    
//    [Vslider setHidden:true];
//    
//    
//    oldframe2=Vslider.frame;
//    
//    [bottomView setHidden:true];
//    
    [self addSubview:self.bottomView];
//
//    [self addSubview:Vslider];
}

#pragma mark - 惰性初始化
- (VMediaPlayer *)mMPayer
{
    if (!_mMPayer) {
        _mMPayer = [[VMediaPlayer alloc] init];
    }
    return _mMPayer;
}

- (UIActivityIndicatorView *)activityView
{
    if (!_activityView) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
                         UIActivityIndicatorViewStyleGray];
        _activityView.backgroundColor=[UIColor clearColor];
    }
    return _activityView;
}

- (UIImageView *)bgImgView
{
    if (!_bgImgView) {
        _bgImgView = [[UIImageView alloc] init];
    }
    return _bgImgView;
}

- (UIButton *)playBtn
{
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"wsmv_poster_play_btn_hl"] forState:UIControlStateNormal];
        [_playBtn setImage:[UIImage imageNamed:@"wsmv_poster_play_btn"] forState:UIControlStateHighlighted];
        [_playBtn addTarget:self action:@selector(PlayBtnAction:)
           forControlEvents:UIControlEventTouchUpInside];
        _playBtn.showsTouchWhenHighlighted = YES;
    }
    return _playBtn;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor clearColor];
    }
    return _bottomView;
}

- (UIButton *)changePlayBtn
{
    if (!_changePlayBtn) {
        _changePlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_changePlayBtn setImage:[UIImage imageNamed:@"wsmv_pause_btn@ios7@2x.png"] forState:UIControlStateNormal];
        [_changePlayBtn setImage:[UIImage imageNamed:@"wsmv_pause_btn_hl@ios7@2x.png"] forState:UIControlStateHighlighted];
        [_changePlayBtn addTarget:self action:@selector(changePlay)
              forControlEvents:UIControlEventTouchUpInside];
        _changePlayBtn.showsTouchWhenHighlighted = YES;
    }
    return _changePlayBtn;
}

- (UILabel *)leftTime
{
    if (!_leftTime) {
        _leftTime = [[UILabel alloc] init];
        _leftTime.font = [UIFont systemFontOfSize:6.0f];
        [_leftTime setTextAlignment:NSTextAlignmentCenter];
        _leftTime.textColor = [UIColor whiteColor];
        _leftTime.backgroundColor = [UIColor clearColor];
        [_leftTime setText:@"0:0:0"];
    }
    return _leftTime;
}

- (UILabel *)rightTime
{
    if (!_rightTime) {
        _rightTime = [[UILabel alloc] initWithFrame:CGRectMake(90+(self.frame.size.width-200), 2, 40, 34)];
        _rightTime.frame = CGRectMake(90 + (self.frame.size.width-200), 2, 40, 34);
        _rightTime.font = [UIFont systemFontOfSize:6.0f];
        [_rightTime setTextAlignment:NSTextAlignmentCenter];
        _rightTime.textColor=[UIColor whiteColor];
        _rightTime.backgroundColor=[UIColor clearColor];
        [_rightTime setText:[self getVideoTotalTime]];
    }
    return _rightTime;
}

- (VSegmentSlider *)progressSld
{
    if (!_progressSld) {
        _progressSld = [[VSegmentSlider alloc] init];
        [_progressSld setMinimumTrackTintColor:[UIColor greenColor]];
        [_progressSld setMaximumTrackTintColor:[UIColor lightGrayColor]];
        [_progressSld setThumbImage:[UIImage imageNamed:@"wsmv_slider_thumb"] forState:UIControlStateNormal];
        [_progressSld setThumbImage:[UIImage imageNamed:@"wsmv_slider_thumb"] forState:UIControlStateHighlighted];
        [_progressSld addTarget:self action:@selector(processCurrentPlaybackTimeChanged:) forControlEvents:UIControlEventValueChanged];
        [_progressSld addTarget:self action:@selector(processCurrentPlaybackTouchBegin:) forControlEvents:UIControlEventTouchDown];
        [_progressSld addTarget:self action:@selector(processCurrentPlaybackTouchEnd:) forControlEvents:UIControlEventTouchUpInside];
        //设置起始位置
        _progressSld.value = 0.0;
        //设置最小数
        _progressSld.minimumValue = 0.0;
        //设置背景颜色
        _progressSld.backgroundColor = [UIColor clearColor];
        _progressSld.continuous = YES;
    }
    return _progressSld;
}

- (UIButton *)screenButton
{
    if (!_screenButton) {
        _screenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_screenButton setImage:[UIImage imageNamed:@"wsmv_fullscreen@ios7@2x.png"] forState:UIControlStateNormal];
        [_screenButton setImage:[UIImage imageNamed:@"wsmv_fullscreen_hl@ios7@2x.png"] forState:UIControlStateHighlighted];
        [_screenButton addTarget:self action:@selector(setFullScreenAct)
                forControlEvents:UIControlEventTouchUpInside];
        _screenButton.showsTouchWhenHighlighted = YES;
    }
    return _screenButton;
}

- (UIButton *)volumnButton
{
    if (!_volumnButton) {
        _volumnButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_volumnButton setImage:[UIImage imageNamed:@"wsmv_volumn@ios7@2x.png"] forState:UIControlStateNormal];
        [_volumnButton setImage:[UIImage imageNamed:@"wsmv_volumn_hl@ios7@2x.png"] forState:UIControlStateHighlighted];
        [_volumnButton addTarget:self action:@selector(showVolumn)
                forControlEvents:UIControlEventTouchUpInside];
        _volumnButton.showsTouchWhenHighlighted = YES;
    }
    return _volumnButton;
}

- (NSURL *)videoURL
{
    if (!_videoURL) {
        _videoURL = [NSURL URLWithString:self.playUrl];
    }
    return _videoURL;
}

- (void)setPlayUrl:(NSString *)playUrl
{
    if (playUrl) {
        _playUrl = playUrl;
        self.videoURL = [NSURL URLWithString:playUrl];
        [self closePlay];
    }
}

#pragma mark - 布局 显示
- (void)setNeedsLayout
{
    [super setNeedsLayout];
    if (self.isFullScreen) {
        if([[UIScreen mainScreen] bounds].size.height == 568){
            self.frame=CGRectMake(0, 0,320, 568);
            self.backgroundColor=[UIColor blackColor];
            self.bottomView.frame=CGRectMake(0, self.frame.size.height-38,self.frame.size.width, 38);
            //Vslider.frame = CGRectMake(270, 50,34, 450);
        }else{
            self.frame=CGRectMake(0, 0,320, 568-88);
            self.backgroundColor=[UIColor blackColor];
            self.bottomView.frame=CGRectMake(0, self.frame.size.height-38,self.frame.size.width, 38);
            //Vslider.frame = CGRectMake(270, 50,34, 450-88);
        }
    } else {
        self.bgImgView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        self.activityView.frame = CGRectMake((self.frame.size.width/2) - 5, (self.frame.size.height/2)-5,10,10);
        self.playBtn.frame = CGRectMake((self.frame.size.width/2) - 29, (self.frame.size.height/2)-28,59,57);
        
        self.bottomView.frame = CGRectMake(0, self.frame.size.height - bottomHeight, self.frame.size.width, bottomHeight);
        self.changePlayBtn.frame = CGRectMake(1, 2, 36, 30);
        self.leftTime.frame = CGRectMake(38, 2, 50, 34);
        self.progressSld.frame = CGRectMake(90, 2, self.frame.size.width - 200, 34);
        self.screenButton.frame = CGRectMake(90+(self.frame.size.width-200) + 40, 2, 36, 30);
        self.volumnButton.frame = CGRectMake(90+(self.frame.size.width-200) + 40 + 35, 2, 36, 30);
    }
}

- (void)upChangePlayBtn{
    if(self.mMPayer.isPlaying){
        [self.changePlayBtn setImage:[UIImage imageNamed:@"wsmv_pause_btn@ios7@2x.png"] forState:UIControlStateNormal];
        [self.changePlayBtn setImage:[UIImage imageNamed:@"wsmv_pause_btn_hl@ios7@2x.png"] forState:UIControlStateHighlighted];
    }else{
        [self.changePlayBtn setImage:[UIImage imageNamed:@"wsmv_play_btn@ios7@2x.png"] forState:UIControlStateNormal];
        [self.changePlayBtn setImage:[UIImage imageNamed:@"wsmv_play_btn_hl@ios7@2x.png"] forState:UIControlStateHighlighted];
    }
}


#pragma mark - 方法总结
- (void)playVideo
{
    //[self closePlay];
    [self.mMPayer setupPlayerWithCarrierView:self withDelegate:self];
    [self.mMPayer setDataSource:self.videoURL];
    [self.mMPayer prepareAsync];
    [self.activityView startAnimating];
    [self.rightTime setText:[self getVideoTotalTime]];
    [self.playBtn setHidden:YES];
}

- (void)closePlay{
    [self.mMPayer reset];
    [self.mMPayer unSetupPlayer];
    [self.activityView stopAnimating];
    [self.bgImgView setHidden:NO];
    [self.playBtn setHidden:NO];
    [self.mSyncSeekTimer invalidate];
}

- (void)changePlay{
    [self.mMPayer isPlaying] ? [self.mMPayer pause] : [self.mMPayer start];
    [self upChangePlayBtn];
}


#pragma mark VMediaPlayerDelegate required
// 当'播放器准备完成'时, 该协议方法被调用, 我们可以在此调用 [player start]
// 来开始音视频的播放.
- (void)mediaPlayer:(VMediaPlayer *)player didPrepared:(id)arg
{
    self.mDuration = [player getDuration];
    [player start];
    [self.bgImgView setHidden:YES];
    [self.activityView stopAnimating];
    self.progressDragging = NO;
    self.mSyncSeekTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(syncUIStatus)
                                                    userInfo:nil
                                                     repeats:YES];
    //[self.bottomView setHidden:false];
    
}
// 当'该音视频播放完毕'时, 该协议方法被调用, 我们可以在此作一些播放器善后
// 操作, 如: 重置播放器, 准备播放下一个音视频等
- (void)mediaPlayer:(VMediaPlayer *)player playbackComplete:(id)arg
{
    [player reset];
    self.mDuration = 0.0f;
    [self.playBtn setHidden:NO];
    [self.mSyncSeekTimer invalidate];
}
- (void)mediaPlayer:(VMediaPlayer *)player error:(id)arg
{
    NSLog(@"NAL 1RRE &&&& VMediaPlayer Error: %@", arg);
    [player reset];
    [self.activityView stopAnimating];
}

#pragma mark VMediaPlayerDelegate Implement / Optional
/*! @brief 打电话时 */
- (void)mediaPlayer:(VMediaPlayer *)player setupManagerPreference:(id)arg
{
    player.decodingSchemeHint = VMDecodingSchemeSoftware;
    player.autoSwitchDecodingScheme = NO;
}
/*! @brief 准备开始 */
- (void)mediaPlayer:(VMediaPlayer *)player setupPlayerPreference:(id)arg
{
    NSLog(@"setupPlayerPreference");
    [player setBufferSize:512*1024];
    [player setVideoQuality:VMVideoQualityHigh];
    player.useCache = YES;
    [player setCacheDirectory:[self getCacheRootDirectory]];
}

- (void)mediaPlayer:(VMediaPlayer *)player seekComplete:(id)arg
{
    NSLog(@"seekComplete");
}

- (void)mediaPlayer:(VMediaPlayer *)player notSeekable:(id)arg
{
}

- (void)mediaPlayer:(VMediaPlayer *)player bufferingStart:(id)arg
{
    if (![Utilities isLocalMedia:self.videoURL]) {
        [player pause];
    }
}

- (void)mediaPlayer:(VMediaPlayer *)player bufferingUpdate:(id)arg
{
//    if(isShowHuncun){
//        self.titleBtl.text = [NSString stringWithFormat:@"%@ [%@]",self.mediaTitle ,[NSString stringWithFormat:@"Buffering... %d%%",[((NSNumber *)arg) intValue]]];
//    }
}
/*! @brief 缓冲结束 */
- (void)mediaPlayer:(VMediaPlayer *)player bufferingEnd:(id)arg
{
    if (![Utilities isLocalMedia:self.videoURL]) {
        [player start];
    }
    self.progressDragging = NO;
}

- (void)mediaPlayer:(VMediaPlayer *)player downloadRate:(id)arg
{
//    if (![Utilities isLocalMedia:self.videoURL]) {
//        if(isShowHuncun){
//            self.titleBtl.text = [NSString stringWithFormat:@"%@ [%dKB/s]",self.mediaTitle ,[arg intValue]];
//        }
//    }
}

- (void)mediaPlayer:(VMediaPlayer *)player videoTrackLagging:(id)arg
{
    //	NSLog(@"NAL 1BGR video lagging....");
}


#pragma mark - 时间进度条
-(void)processCurrentPlaybackTimeChanged:(id)sender
{
    float seek = self.progressSld.value * self.mDuration;
    self.leftTime.text = [Utilities timeToHumanString:seek];
    [self.mMPayer seekTo:seek];
}

-(void)processCurrentPlaybackTouchBegin:(id)sender
{
    [self.mMPayer pause];
    self.progressDragging = YES;
}

-(void)processCurrentPlaybackTouchEnd:(id)sender
{
    [self.mMPayer start];
}

#pragma mark - 内部方法
- (void)PlayBtnAction:(id)sender{
    
    UIButton *clicked = (UIButton *) sender;
    [clicked setShowsTouchWhenHighlighted:YES];
    [clicked setHidden:YES];
    [self playVideo];
}

- (void)setFullScreenAct{
    self.isFullScreen = !self.isFullScreen;
    NSLog(@"需要做全屏处理");
}

- (void)showVolumn{
    
    //_isVoice=!_isVoice;
    
}

- (NSString*)getVideoTotalTime{
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:self.videoURL options:nil];
    // 初始化视频媒体文件
    int minute = 0, second = 0,hour=0;
    second = (int)(urlAsset.duration.value / urlAsset.duration.timescale);
    // 获取视频总时长,单位秒
    NSLog(@"movie duration : %d", second);
    if (second >= 3600) {
        int index = second / 3600;
        hour = index;
        second = second - index*3600;
    }
    if (second >= 60) {
        int index = second / 60;
        minute = index;
        second = second - index*60;
    }
    return [NSString stringWithFormat:@"%d:%d:%d",hour,minute,second];
}

- (NSString *)getCacheRootDirectory
{
    NSString *cache = [NSString stringWithFormat:@"%@/Library/Caches/MediasCaches", NSHomeDirectory()];
    if (![[NSFileManager defaultManager] fileExistsAtPath:cache]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cache
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    return cache;
}

#pragma mark - 更新进度条
-(void)syncUIStatus
{
    if(self.mMPayer.isPlaying){
        if (!self.progressDragging) {
            float mCurPostion  = [self.mMPayer getCurrentPosition];
            [self.progressSld setValue:mCurPostion/self.mDuration];
            [self.leftTime setText:[Utilities timeToHumanString:mCurPostion]];
            [self.rightTime setText:[Utilities timeToHumanString:self.mDuration]];
            self.rightTime.text = [Utilities timeToHumanString:self.mDuration];
            
            //[self isJustVideoBarShow];
            
            [self upChangePlayBtn];
            
            //[self drawVolumnVoiceSlider];
            
        }else{
            
            return;
        }
    }
}



@end
